package com.zcxy.fast.utils;


import com.zcxy.fast.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author zcc
 * @create 2019/10/13 19:32
 * @Ver 1.0.0
 */
@Component
@Slf4j
public class MessageSourceUtil {
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private HttpServletRequest request;

    public String getMessage(String code) {
        return getMessage(code, null);
    }

    public String getMessage(String code, Object[] args) {
        return getMessage(code, args, "");
    }

    public String getMessage(String code, Object[] args, String defaultMsg) {
        // 这里使用比较方便的方法，不依赖request.
        String lang = request.getHeader(CommonConstant.X_ACCESS_LANG);
        if (StringUtils.isEmpty(lang)) {
            lang = CommonConstant.ZH_LANG;
        }
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(lang) ) {
            locale = new Locale(lang);
        }
        try {
            return messageSource.getMessage(code, args, locale);
        } catch (NoSuchMessageException e) {
            log.warn("本地化异常消息异常:{},{}", code, args);
            return defaultMsg;
        }
    }

}